package com.nuanshui.heatedloan.extension.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

/**
 * UserFilter
 * 
 *
 */
public class UserFilter extends AccessControlFilter {

	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if (isLoginRequest(request, response)) {
			return true;
		} else {
			Subject subject = getSubject(request, response);
			return subject.getPrincipal() != null;
		}
	}

	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		final HttpServletRequest httpRequest = (HttpServletRequest) request;
		final HttpServletResponse httpResponse = (HttpServletResponse) response;
		if (isAjax(httpRequest)) {
			sendJson(httpResponse, 403, "未登录");
			return false;
		}
		saveRequestAndRedirectToLogin(request, response);
		return false;
	}

	public static boolean isAjax(HttpServletRequest httpRequest) {
		return "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"));
	}

	public static void sendJson(HttpServletResponse httpResponse, int code, String msg) {
		try {
			httpResponse.setHeader("Content-Type", "application/json;charset=utf-8");
			httpResponse.getWriter().write("{\"code\":" + code + ",\"msg\":\"" + msg + "\"}");
			httpResponse.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
